package com.augurit.wf.client.summary.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jbpm.api.history.HistoryProcessInstance;
import org.jbpm.api.history.HistoryTask;
import org.jbpm.api.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;

import com.augurit.common.util.PageUtils;
import com.augurit.wf.client.summary.convert.WfTaskSummaryConvertor;
import com.augurit.wf.client.summary.service.IWfTaskSummaryService;
import com.augurit.wf.client.summary.web.form.WfTaskSummaryForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.dao.Jbpm4HistTaskDao;
import com.augurit.wf.common.extmodel.SummaryCountNode;
import com.augurit.wf.common.util.WfUtils;

@Service
@Transactional
public class WfTaskSummaryServiceImpl implements IWfTaskSummaryService{

	private static final String DZB_PART_HQL = "from Jbpm4HistTask task, Jbpm4HistProcinst proc, WfBusInstance inst, WfBusTemplate temp, WfBusTemplateType type" +
			" where task.procInstId = proc.procInstId and proc.procInstId = inst.procInstId" +
			" and inst.templateId = temp.id and temp.templateTypeId = type.id" +
			" and proc.state=:procState and (task.assignee=:taskAssignee or (task.agent=:taskAssignee and task.agentStartDate<:now and task.agentEndDate>:now))";
	
	private static final String DZB_HQL = "select task, proc, inst, temp.templateName, type.templateTypeName " + DZB_PART_HQL;
	
	private static final String DZB_COUNT_HQL = DZB_PART_HQL + " and task.state=:taskState";

	@Autowired
	private Jbpm4HistTaskDao jbpm4HistTaskDao;
	
	
	
	@Transactional(readOnly = true)
	public Page<WfTaskSummaryForm> getSummary(String taskType, Page<WfTaskSummaryForm> page, WfTaskSummaryForm form, String userKey, String groupBy, String groupDir) {
		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);
		
		// 查询语句及参数
		StringBuffer hql = new StringBuffer(DZB_HQL);
		Map<String, Object> values = new HashMap();
		
		values.put("procState", HistoryProcessInstance.STATE_ACTIVE);
		values.put("taskAssignee", userKey);
		values.put("now", new Date());
		
		// 添加任务类型过滤条件
		if(taskType != null && taskType.trim().length() > 0){
			if(taskType.equals(WfConstant.TASK_SUMMARY_TYPE_DB)){
				hql.append(" and task.signTime is null and task.state = :taskState");
				values.put("taskState", Task.STATE_OPEN);
			}
			else if(taskType.equals(WfConstant.TASK_SUMMARY_TYPE_ZB)){
				hql.append(" and task.signTime is not null and task.state = :taskState");
				values.put("taskState", Task.STATE_OPEN);
			}
			else if(taskType.equals(WfConstant.TASK_SUMMARY_TYPE_DZB)){
				hql.append(" and task.state = :taskState");
				values.put("taskState", Task.STATE_OPEN);
			}
		}
		
		// 查询条件
		if(form != null){
//			if(form.getKeyWord() != null && form.getKeyWord().trim().length()>0){
//				hql.append(" and (");
//				
//				hql.append(" inst.busMemo1 like :busMemo1");
//				values.put("busMemo1", "%"+form.getKeyWord()+"%");
//				
//				hql.append(" or inst.busMemo2 like :busMemo2");
//				values.put("busMemo2", "%"+form.getKeyWord()+"%");
//				
//				hql.append(" or inst.busMemo3 like :busMemo3");
//				values.put("busMemo3", "%"+form.getKeyWord()+"%");
//				
//				hql.append(" or inst.busMemo4 like :busMemo4");
//				values.put("busMemo4", "%"+form.getKeyWord()+"%");
//				
//				hql.append(" or inst.busMemo5 like :busMemo5");
//				values.put("busMemo5", "%"+form.getKeyWord()+"%");
//				
//				hql.append(" or inst.busMemo6 like :busMemo6");
//				values.put("busMemo6", "%"+form.getKeyWord()+"%");
//				
//				hql.append(" )");
//			}
			
			
			/**     城管委开始       */
			if(form.getBusMemo1() != null && form.getBusMemo1().trim().length() > 0){
				hql.append(" and inst.busMemo1 like :busMemo1");
				values.put("busMemo1", "%"+form.getBusMemo1()+"%");
			}
			if(form.getBusMemo2() != null && form.getBusMemo2().trim().length() > 0){
				hql.append(" and inst.busMemo2 like :busMemo2");
				values.put("busMemo2", "%"+form.getBusMemo2()+"%");
			}
			if(form.getBusMemo3() != null && form.getBusMemo3().trim().length() > 0){
				hql.append(" and inst.busMemo3 like :busMemo3");
				values.put("busMemo3", "%"+form.getBusMemo3()+"%");
			}
			if(form.getBusMemo4() != null && form.getBusMemo4().trim().length() > 0){
				hql.append(" and inst.busMemo4 like :busMemo4");
				values.put("busMemo4", "%"+form.getBusMemo4()+"%");
			}
			if(form.getBusMemo5() != null && form.getBusMemo5().trim().length() > 0){
				hql.append(" and inst.busMemo5 like :busMemo5");
				values.put("busMemo5", "%"+form.getBusMemo5()+"%");
			}
			
			if(form.getBusDate2() != null){
				//String d1=sdf.format(form.getBusDate2());
				hql.append(" and inst.busDate2>= :busDate2");
				values.put("busDate2", form.getBusDate2());
			}			
			//结束时间
			if(form.getBusDate3() != null){
				//String d2=sdf.format(form.getBusDate3());
				hql.append(" and inst.busDate3 <= :busDate3");
				values.put("busDate3", form.getBusDate3());
			}
			/**     城管委结束       */
		}

		//排序
		hql.append(WfUtils.buildTaskSummaryOrderBy("task", "inst", "temp", "type", page, groupBy, groupDir));
		
		// 执行分页查询操作
		jbpm4HistTaskDao.findPage(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<WfTaskSummaryForm> list = WfTaskSummaryConvertor.convertToTaskSummaryList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}

	@Transactional(readOnly = true)
	public Page<WfTaskSummaryForm> getDbSummary(Page<WfTaskSummaryForm> page, WfTaskSummaryForm form, String userKey, String groupBy, String groupDir){
		return this.getSummary(WfConstant.TASK_SUMMARY_TYPE_DB, page, form, userKey, groupBy, groupDir);
	}
	
	@Transactional(readOnly = true)
	public Page<WfTaskSummaryForm> getZbSummary(Page<WfTaskSummaryForm> page, WfTaskSummaryForm form, String userKey, String groupBy, String groupDir){
		return this.getSummary(WfConstant.TASK_SUMMARY_TYPE_ZB, page, form, userKey, groupBy, groupDir);
	}
	
	@Transactional(readOnly = true)
	public Page<WfTaskSummaryForm> getDbAndZbSummary(Page<WfTaskSummaryForm> page, WfTaskSummaryForm form, String userKey, String groupBy, String groupDir){
		return this.getSummary(WfConstant.TASK_SUMMARY_TYPE_DZB, page, form, userKey, groupBy, groupDir);
	}
	
	@Transactional(readOnly = true)
	public Page<WfTaskSummaryForm> getYbSummary(Page<WfTaskSummaryForm> page, WfTaskSummaryForm form, String userKey, String groupBy, String groupDir){
		return this.getYbSummary(HistoryProcessInstance.STATE_ACTIVE, page, form, userKey, groupBy, groupDir);
	}
	
	@Transactional(readOnly = true)
	public Page<WfTaskSummaryForm> getBjSummary(Page<WfTaskSummaryForm> page, WfTaskSummaryForm form, String userKey, String groupBy, String groupDir){
		return this.getYbSummary(HistoryProcessInstance.STATE_ENDED, page, form, userKey, groupBy, groupDir);
	}
	
	@Transactional(readOnly = true)
	public Page<WfTaskSummaryForm> getYbSummary(String procState, Page<WfTaskSummaryForm> page, WfTaskSummaryForm form, String userKey, String groupBy, String groupDir){
		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);
		
		// 查询语句及参数
		String tempHql = "select distinct inst, proc, temp.templateName, type.templateTypeName" +
				" from Jbpm4HistTask task, Jbpm4HistProcinst proc, WfBusInstance inst, WfBusTemplate temp, WfBusTemplateType type" +
				" where task.procInstId = proc.procInstId and proc.procInstId = inst.procInstId" +
				" and inst.templateId = temp.id and temp.templateTypeId = type.id" +
				" and proc.state=:procState and task.state=:taskState" +
				" and (task.assignee=:taskAssignee or (task.agent=:taskAssignee and task.agentStartDate<:now and task.agentEndDate>:now))";

//		select distinct inst.*, proc.*, temp.template_Name, type.template_Type_Name 
//		from Jbpm4_Hist_Task task, Jbpm4_Hist_Procinst proc, Wf_Bus_Instance inst, Wf_Bus_Template temp, Wf_Bus_Template_Type type 
//		where task.PROCINST_ = proc.Id_ and proc.Id_ = inst.proc_Inst_Id and inst.template_Id = temp.id and temp.template_Type_Id = type.id 
//		and proc.state_='active' and task.state_='completed' and task.assignee_='aosadmin'
		
		StringBuffer hql = new StringBuffer(tempHql);
		Map<String, Object> values = new HashMap();
		values.put("taskAssignee", userKey);
		values.put("now", new Date());
		values.put("procState", procState);
		values.put("taskState", HistoryTask.STATE_COMPLETED);
		
		// 查询条件
		if(form != null){
//			if(form.getKeyWord() != null && form.getKeyWord().trim().length()>0){
//				hql.append(" and (");
//				
//				hql.append(" inst.busMemo1 like :busMemo1");
//				values.put("busMemo1", "%"+form.getKeyWord()+"%");
//				
//				hql.append(" or inst.busMemo2 like :busMemo2");
//				values.put("busMemo2", "%"+form.getKeyWord()+"%");
//				
//				hql.append(" or inst.busMemo3 like :busMemo3");
//				values.put("busMemo3", "%"+form.getKeyWord()+"%");
//				
//				hql.append(" or inst.busMemo4 like :busMemo4");
//				values.put("busMemo4", "%"+form.getKeyWord()+"%");
//				
//				hql.append(" or inst.busMemo5 like :busMemo5");
//				values.put("busMemo5", "%"+form.getKeyWord()+"%");
//				
//				hql.append(" or inst.busMemo6 like :busMemo6");
//				values.put("busMemo6", "%"+form.getKeyWord()+"%");
//				
//				hql.append(" )");
//			}
			
			/**     城管委开始       */
			if(form.getBusMemo1() != null && form.getBusMemo1().trim().length() > 0){
				hql.append(" and inst.busMemo1 like :busMemo1");
				values.put("busMemo1", "%"+form.getBusMemo1()+"%");
			}
			if(form.getBusMemo2() != null && form.getBusMemo2().trim().length() > 0){
				hql.append(" and inst.busMemo2 like :busMemo2");
				values.put("busMemo2", "%"+form.getBusMemo2()+"%");
			}
			if(form.getBusMemo3() != null && form.getBusMemo3().trim().length() > 0){
				hql.append(" and inst.busMemo3 like :busMemo3");
				values.put("busMemo3", "%"+form.getBusMemo3()+"%");
			}
			if(form.getBusMemo4() != null && form.getBusMemo4().trim().length() > 0){
				hql.append(" and inst.busMemo4 like :busMemo4");
				values.put("busMemo4", "%"+form.getBusMemo4()+"%");
			}
			if(form.getBusMemo5() != null && form.getBusMemo5().trim().length() > 0){
				hql.append(" and inst.busMemo5 like :busMemo5");
				values.put("busMemo5", "%"+form.getBusMemo5()+"%");
			}
			
			if(form.getBusDate2() != null){
				//String d1=sdf.format(form.getBusDate2());
				hql.append(" and inst.busDate2>= :busDate2");
				values.put("busDate2", form.getBusDate2());
			}			
			//结束时间
			if(form.getBusDate3() != null){
				//String d2=sdf.format(form.getBusDate3());
				hql.append(" and inst.busDate3 <= :busDate3");
				values.put("busDate3", form.getBusDate3());
			}
			/**     城管委结束       */
		}
		
		//排序
		hql.append(WfUtils.buildBusSummaryOrderBy("inst", "proc", "temp", "type", page, groupBy, groupDir));
		
		// 执行分页查询操作
		jbpm4HistTaskDao.findPageByScrollMode(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<WfTaskSummaryForm> list = WfTaskSummaryConvertor.convertBusSummaryList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}
	
	@Transactional(readOnly = true)
	public List<SummaryCountNode> getSummaryCount(String userKey, WfTaskSummaryForm form){
		if(form != null)
			return this.getSummaryCount(userKey, form.getGroupByProperty(), form.getTemplateTypeName());
		else
			return null;
	}
	
	@Transactional(readOnly = true)
	private List<SummaryCountNode> getSummaryCount(String userKey, String groupByProperty, String templateTypeName){
		if(userKey != null && userKey.trim().length() > 0
				&& groupByProperty != null && groupByProperty.trim().length() > 0){
			
			String selectGroupByProperty = "";
			String countGroupByProperty = "";
			if(groupByProperty.equals("templateTypeName")){
				selectGroupByProperty = "type.templateTypeName";
				countGroupByProperty = "type.templateTypeName";
			}
			else if(groupByProperty.equals("templateName")){
				selectGroupByProperty = "temp.templateName";
				countGroupByProperty = "temp.templateName";
			}
			
			
			String hql = "select " + selectGroupByProperty + ", count(" + countGroupByProperty + ") " + DZB_COUNT_HQL;
			
			if(templateTypeName != null && templateTypeName.trim().length() > 0){
				hql += " and type.templateTypeName=:templateTypeName";
			}
			
			hql += " group by " + countGroupByProperty;
			
			Map<String, Object> values = new HashMap();
			values.put("taskAssignee", userKey);
			values.put("now", new Date());
			values.put("templateTypeName", templateTypeName);
			values.put("procState", HistoryProcessInstance.STATE_ACTIVE);
			values.put("taskState", Task.STATE_OPEN);

			List<Object[]> list = jbpm4HistTaskDao.find(hql, values);
			return WfTaskSummaryConvertor.convertToExtModel(groupByProperty, templateTypeName, list);
		}
		return null;
	}
}
